/**
 * Created by Administrator on 2017/4/6 0006.
 */
var React = require('react');


var Bheader = require('../widget/Bheader');
var Footer = require('../widget/Footer');
var Cart = require('../widget/Cart');
var ajax = require('../tools/ajax');
var IncreaseId = require('../../web/tools/IncreaseId');
var Icon = require('../components/Icon');
var MsgBox = require('../components/MsgBox');

module.exports = React.createClass({
    getInitialState: function () {
        return {
            theme:"Default", //Default/Blue
            shopIdList:[],//店铺ID
            shopList:"",//列表Dom
            shopCheck:{},//选中店铺
            bianjiFlag:false,//编辑按钮
            totalAllPrice:0,//总价合计
            price:0,
            oneTotalPrice:{},
            ckAll:false,//全选判断
            shipping_money:0//运费
        }
    },
    myScroll:"",

    componentDidMount: function () {
        this.getCartShopid();
        setTimeout(this.iscroll,1000);
    },

    componentDidUpdate() {
        if(this.myScroll){
            this.myScroll.refresh();
        }
    },
    /**iScroll插件*/
    iscroll(){
        var p =this;
        p.myScroll = new IScroll("#cartWrapper",{
            // 默认iscroll会拦截元素的默认事件处理函数，我们需要响应onClick，因此要配置
            preventDefault: false,
            // 禁止缩放
            zoom: false,
            // 支持鼠标事件，因为我开发是PC鼠标模拟的
            mouseWheel: true,
            // 滚动事件的探测灵敏度，1-3，越高越灵敏，兼容性越好，性能越差
            probeType: 3,
            // 拖拽超过上下界后出现弹射动画效果，用于实现下拉/上拉刷新
            bounce: true,
            // 展示滚动条
            scrollbars: false
        });
        p.myScroll.refresh();
        document.addEventListener('touchmove', function(){}, false);
    },

    /**编辑按钮*/
    bianji(){
        var bianjiFlag = this.state.bianjiFlag;
        if(bianjiFlag){
            this.setState({bianjiFlag:false})
        }else{
            this.setState({bianjiFlag:true})
        }
    },
    /**获取购物车店铺信息*/
    getCartShopid(){
        var p = this;
        var userId = localStorage.getItem('userId');
        if(userId){
            ajax("POST","getCartShopid",{user_id:userId},function(dt){
                if(dt&&dt.success){
                    var objs = dt.data;
                    var shopCheck = {};
                    for(var i=0;i<objs.length;i++){
                        shopCheck[objs[i].shop_id] = false;
                    }
                    p.setState({shopIdList:objs,shopCheck:shopCheck});
                }
            });
        }else{
            location.href = '#login';
        }
    },
    /**选中店铺*/
    shopCheck(e){
        var p=this;
        var shopId = e.currentTarget.getAttribute("data");
        var shopChecked = this.refs["cart"+shopId].state.shopChecked;
        var shopCheck = p.state.shopCheck;
        console.log(shopCheck);
        shopChecked[shopId] = !shopChecked[shopId];
        shopCheck[shopId] = !shopCheck[shopId];
        p.refs["cart"+shopId].setState({shopChecked:shopChecked,shopId:shopId});
        //修改选中店铺下商品状态
        var goodsChecked = this.refs["cart"+shopId].state.goodsChecked;
        //计算店铺选中下的商品全金额
        var oneTotalPrice = p.refs["cart"+shopId].state.oneTotalPrice;
        var totalAllPrice = p.state.totalAllPrice;
        var totalPrice =0;
        for (var j in oneTotalPrice){
            if(shopCheck[shopId]) {
                totalAllPrice = (parseFloat(totalAllPrice*100 + oneTotalPrice[j]*100)/100).toFixed(2);
                totalPrice = (parseFloat(totalPrice*100 + oneTotalPrice[j]*100)/100).toFixed(2);
                if (goodsChecked[j]) {
                    totalAllPrice = (parseFloat(totalAllPrice*100 - oneTotalPrice[j]*100)/100).toFixed(2);
                }
            }else{
                totalAllPrice =(parseFloat(totalAllPrice*100 - oneTotalPrice[j]*100)/100).toFixed(2);
            }
        }
        console.log(totalPrice);
        p.refs["cart"+shopId].setState({totalPrice:totalPrice});
        for (var i in goodsChecked) {
            goodsChecked[i] = shopCheck[shopId];
        }
        var flag = false;
        for(var k in shopCheck){
            if(shopCheck[k]){
                flag = true;
            }else{
                flag = false;
                break;
            }
        }
        console.log(flag);
        p.setState({
            shopCheck:shopCheck,
            totalAllPrice:totalAllPrice,
            ckAll:flag
        });
    },
    /**单选判断*/
    sc(){
        var shopIdList =this.state.shopIdList;
        var sc={};
        for(var i=0;i<shopIdList.length;i++) {
            var shopChecked = this.refs["cart" + shopIdList[i].shop_id].state.shopChecked;
            sc = Object.assign(sc,shopChecked);
        }
        var flag = false;
        for(var i in sc){
            if(sc[i]){
                flag = true;
            }else{
                flag = false;
                break;
            }
        }
        this.setState({shopCheck:sc,ckAll:flag});
    },
    /**全选*/
    ckall(){
        var p =this;
        var shopIdList = p.state.shopIdList;
        var shopCheck = p.state.shopCheck;
        var ckAll = p.state.ckAll;
        var totalAllPrice =0;
        ckAll = !ckAll;
        for(var i=0;i<shopIdList.length;i++){
            var shopChecked = this.refs["cart"+shopIdList[i].shop_id].state.shopChecked;
            var goodsChecked = p.refs["cart"+shopIdList[i].shop_id].state.goodsChecked;
            var oneTotalPrice = p.refs["cart"+shopIdList[i].shop_id].state.oneTotalPrice;
            var totalPrice = 0.00;
            for(var j in goodsChecked){
                goodsChecked[j] = ckAll;
                if(ckAll){
                    totalPrice = (parseInt(totalPrice*100 + oneTotalPrice[j]*100)/100).toFixed(2);
                    p.refs["cart"+shopIdList[i].shop_id].setState({totalPrice:totalPrice});
                }
            }
            for(var k in oneTotalPrice){
                if(ckAll){
                    totalAllPrice = (parseInt(totalAllPrice*100 + oneTotalPrice[k]*100)/100).toFixed(2);
                }else{
                    totalAllPrice = 0;
                    p.refs["cart"+shopIdList[i].shop_id].setState({totalPrice:0});
                }
            }
            shopChecked[shopIdList[i].shop_id] = ckAll;
            p.refs["cart"+shopIdList[i].shop_id].setState({
                shopChecked:shopChecked,
                goodsChecked:goodsChecked
            });
            shopCheck[shopIdList[i].shop_id] = ckAll;
        }
        p.setState({totalAllPrice:totalAllPrice,shopCheck:shopCheck,ckAll:ckAll});
    },
    /**结算(添加商品信息)*/
    addOrderGoods:function(){
        var p = this;
        var userId = localStorage.getItem('userId');
        var shopIdList = p.state.shopIdList;
        if(userId) {
            var gc = false;
            var order_id = IncreaseId.increaseId();
            var good_tax = 0;
            for (var i = 0; i < shopIdList.length; i++) {
                var cartList = p.refs["cart" + shopIdList[i].shop_id].state.cartList;
                console.log(cartList);
                var goodsChecked = p.refs["cart" + shopIdList[i].shop_id].state.goodsChecked;
                for(var j =0;j <cartList.length;j++){
                    if(goodsChecked[shopIdList[i].shop_id+cartList[j].goods_id]) {
                        gc = true;
                        good_tax += cartList[j].good_tax_fee * cartList[j].goods_number;
                        var goods_id = cartList[j].goods_id,
                            goods_number = cartList[j].goods_number;
                        console.log(cartList[j]);
                        ajax("POST", "addOrderGoods", {
                            order_id:order_id,
                            shop_id:shopIdList[i].shop_id,
                            goods_id:goods_id,
                            goods_name:cartList[j].goods_name,
                            goods_price:cartList[j].goods_price,
                            goods_number:goods_number,
                            goods_type:cartList[j].goods_type,
                            goods_attr:cartList[j].goods_attr,
                            good_tax_fee:cartList[j].good_tax_fee,
                            is_discount:cartList[j].is_discount
                        }, function (dt) {
                            if (dt && dt.success) {
                                console.log(">>>"+goods_id);
                                ajax("POST", "updateKucun", {goods_id:goods_id,goods_number:goods_number,},function (dt) {
                                    if (dt && dt.success) {
                                        console.log("库存更新");
                                    }
                                });
                            }
                        });
                    }
                }
            }
            if(!gc){
                p.refs.MsgBox.setState({
                    type: "no",
                    timeout:1000,
                    show:true,
                    word:"请选择需要结算的商品"
                })
            }else{
                ajax("POST","getShipping",{order_id:order_id},function(dt){
                    if(dt && dt.success){
                        var shipping_money = dt.data.shipping_money;
                        p.setState({shipping_money:shipping_money},()=>{
                            p.addOrderInfo(userId, order_id, good_tax);
                        });
                    }
                });
            }
        }else{
            location.href = '#login';
        }
    },
    /**结算(添加order_info信息)*/
    addOrderInfo: function (userId,order_id,good_tax) {
        this.deleteCartProByGoodsId();
        var order_sn = this.orderSn();
        var order_status = 0;
        var shipping_status = 0;
        var pay_status = 0;
        var goods_amount = this.state.totalAllPrice;
        var shipping_fee = this.state.shipping_money;
        var order_amount = (parseInt(goods_amount*100 + good_tax*100 + shipping_fee*100)/100).toFixed(2);
        console.log(order_amount);
        var add_time = new Date().getTime();
        ajax("POST","addOrderInfo",{
            orderId:order_id,
            order_sn:order_sn,
            user_id:userId,
            order_status:order_status,
            shipping_status:shipping_status,
            pay_status:pay_status,
            goods_amount:goods_amount,
            shipping_fee:shipping_fee,
            order_amount:order_amount,
            goods_tax:good_tax,
            add_time:add_time
        },function(dt){
            if(dt && dt.success){
                localStorage.setItem("orderId",order_id);
                location.href = '#orderInfo';
            }
        });
    },
    shipping(){
        var p=this;
        ajax("POST","getShipping",{userId:userId,orderId:orderId},function(dt){
            if(dt && dt.success){
                var shipping_money = dt.data.shipping_money;
                p.setState({shipping_money:shipping_money});
            }
        });
    },
    /**生成order_sn*/
    orderSn(){
        var now = new Date();
        var year = now.getFullYear();       //年
        var month = now.getMonth() + 1;     //月
        var day = now.getDate();            //日
        var clock = year;
        if(month < 10) {
            clock = clock+ "0" + month;
        }else{
            clock +=month;
        }
        if(day < 10) {
            clock = clock+ "0" + day;
        }else{
            clock +=day;
        }
        var random ='';
        for(var i=0;i<6;i++){
            random += Math.floor(Math.random()*10);
        }
        clock += random;
        return(clock);
    },
    /**删除购物车商品*/
    deleteCartProByGoodsId(){
        var p =this;
        var user_id = localStorage.getItem("userId");
        var shopIdList = p.state.shopIdList;
        var shopCheck = p.state.shopCheck;
        for(var i=0;i<shopIdList.length;i++){
            var goodsChecked = p.refs["cart"+shopIdList[i].shop_id].state.goodsChecked;
            for(var j in goodsChecked){
                if(goodsChecked[j]){
                    var goods_id = j.replace(shopIdList[i].shop_id,"");
                    ajax("POST","deleteCartProByGoodsId",{
                        user_id:user_id,
                        goods_id:goods_id,
                        shop_id:shopIdList[i].shop_id
                    },function(dt){
                        if(dt&&dt.success){
                            console.log("删除成功");
                            localStorage.cartNum -= 1;
                        }
                    });
                }
            }
            p.refs["cart"+shopIdList[i].shop_id].getCartByShopid();
        }
        for(var j in shopCheck){
            if(shopCheck[j]){
                this.getCartShopid();
            }
        }
        p.setState({totalAllPrice:0,ckAll:false});
    },
    //计算总价
    allTotal(){
        var p =this;
        var shopIdList = this.state.shopIdList;
        var totalAllPrice = 0;
        for(var i=0;i<shopIdList.length;i++){
            var totalPrice = parseFloat(this.refs["cart"+shopIdList[i].shop_id].state.totalPrice).toFixed(2);
            console.log(totalPrice)
            totalAllPrice =(parseInt(totalAllPrice * 100 + totalPrice * 100) / 100).toFixed(2);
        }
        console.log(">>>"+totalAllPrice);
        this.setState({totalAllPrice:totalAllPrice});
    },
    /**购物车数量*/
    cartNum(){
        var shopIdList = this.state.shopIdList;
        localStorage.cartNum = 0;
        for(var i=0;i<shopIdList.length;i++) {
            var cartNum = this.refs["cart" + shopIdList[i].shop_id].state.cartNum;
            var num = cartNum[shopIdList[i].shop_id];
            localStorage.cartNum = parseInt(localStorage.cartNum) + num;
        }
    },
    /**限购提示*/
    msg(){
        this.refs.MsgBox.setState({
            type: "no",
            timeout:1000,
            show:true,
            word:"打折商品限购一件"
        })
    },
    render: function () {
        var p = this;
        var shopIdList = p.state.shopIdList;
        var shopList = shopIdList.map(function(obj,index){
            return(
                <div key={index} className="shop">
                    <div className={p.state.shopCheck[obj.shop_id]?"cart_header checked":"cart_header"} onClick={p.shopCheck} data={obj.shop_id}>
                        <Icon icon="#icon-xuanzhong1"></Icon>
                        <p>{obj.shopname?obj.shopname:"跨乐购平台"}</p>
                    </div>
                    <Cart ref={"cart"+obj.shop_id} msg={p.msg} cartNum={p.cartNum} sc={p.sc} allTotal={p.allTotal} data-shopId={obj.shop_id} shopId={obj.shop_id}/>
                </div>
            )
        });
        return (
            <div className="main"  id="main">
                <Bheader ref="bianji" cartNum={p.cartNum} theme={p.state.theme} title="购物车" headr="false" hact="#"></Bheader>
                <div className="bianji" onClick={p.bianji}>编辑</div>
                <div id="cartWrapper" className="container-t wrap">
                    <div style={{minHeight:"28.66rem"}}>
                        {shopList}
                        <MsgBox ref="MsgBox"></MsgBox>
                    </div>
                </div>
                <div className="cart_footer">
                    <div className="whole">
                        <div className={p.state.ckAll?"cartIcon checked":"cartIcon"} onClick={p.ckall}>
                            <Icon icon="#icon-xuanzhong1"></Icon>
                        </div>
                        <p className="all">全选</p>
                        <p className="total" style={{display: p.state.bianjiFlag ? "none":"block"}}>
                            合计：<span className="allPrice">{p.state.totalAllPrice}</span>
                            <span>元</span>
                        </p>
                    </div>
                    <div className="count" onClick={p.state.bianjiFlag ? p.deleteCartProByGoodsId : p.addOrderGoods}>
                        <p>{p.state.bianjiFlag ? "删除" : "结算"}</p>
                    </div>
                </div>
            </div>
        )
    }
});

